package cn.edu.zut.response;

import cn.edu.zut.mapper.UserMapper;
import cn.edu.zut.pojo.User;
import cn.edu.zut.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Davey chan
 */
@WebServlet("/registerServlet")
public class registerServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
//        创建一个User对象
       User user=new User();
       user.setUsername(username);
       user.setPassword(password);

        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
//        获取sqlsesion对象
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
//      获取mapper对象
        UserMapper usermapper = sqlSession.getMapper(UserMapper.class);
//
        User u = usermapper.selectByusername(username);

        if(u==null){
//           用户名不存在，可以注册
            usermapper.add(user);
//            提交事务
            sqlSession.commit();
//          释放
            sqlSession.close();
        }else{
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("用户名已存在");


        }


    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }


}
